<template>
  <div class="product-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>商品管理</span>
          <div class="header-right">
            <el-button type="primary" @click="handleAdd">添加商品</el-button>
          </div>
        </div>
      </template>

      <!-- 搜索栏 -->
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="商品名称">
          <el-input v-model="searchForm.name" placeholder="请输入商品名称" clearable />
        </el-form-item>
        <el-form-item label="分类">
          <el-select v-model="searchForm.categoryId" placeholder="请选择分类" clearable>
            <el-option
              v-for="item in categories"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="上架" :value="1" />
            <el-option label="下架" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 商品列表 -->
      <el-table
        v-loading="loading"
        :data="productList"
        style="width: 100%"
        @expand-change="handleExpandChange"
      >
        <el-table-column type="expand">
          <template #default="{ row }">
            <div v-loading="row.skuLoading" class="sku-expand">
              <el-table
                v-if="row.skuList && row.skuList.length > 0"
                :data="row.skuList"
                style="width: 100%"
                size="small"
                border
              >
                <el-table-column label="SKU名称" prop="skuName" min-width="150" show-overflow-tooltip />
                <el-table-column label="规格" min-width="200">
                  <template #default="{ row: sku }">
                    <div class="sku-specs">
                      <el-tag
                        v-for="(value, name) in parseSpecValues(sku.specValues)"
                        :key="name"
                        size="small"
                        class="sku-spec-tag"
                      >
                        {{ name }}: {{ value }}
                      </el-tag>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column label="SKU图片" width="80">
                  <template #default="{ row: sku }">
                    <el-image
                      v-if="sku.image"
                      :src="sku.image"
                      :preview-src-list="[sku.image]"
                      fit="cover"
                      class="sku-image"
                    />
                    <span v-else>暂无图片</span>
                  </template>
                </el-table-column>
                <el-table-column prop="price" label="价格" width="120">
                  <template #default="{ row: sku }">
                    <span class="price">¥{{ formatPrice(sku.price) }}</span>
                  </template>
                </el-table-column>
                <el-table-column prop="stock" label="库存" width="100" />
                <el-table-column label="状态" width="100">
                  <template #default="{ row: sku }">
                    <el-tag :type="sku.status === 1 ? 'success' : 'info'">
                      {{ sku.status === 1 ? '启用' : '禁用' }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="150" fixed="right">
                  <template #default="{ row: sku }">
                    <el-button-group>
                      <el-button
                        type="primary"
                        link
                        @click="handleEditSku(row, sku)"
                      >编辑</el-button>
                      <el-button
                        :type="sku.status === 1 ? 'warning' : 'success'"
                        link
                        @click="handleToggleSkuStatus(row, sku)"
                      >
                        {{ sku.status === 1 ? '禁用' : '启用' }}
                      </el-button>
                      <el-button
                        type="danger"
                        link
                        @click="handleDeleteSku(row, sku)"
                      >删除</el-button>
                    </el-button-group>
                  </template>
                </el-table-column>
              </el-table>
              <div v-else class="no-sku">
                该商品暂无SKU信息
              </div>
              <!-- 添加SKU按钮 -->
              <div class="sku-actions">
                <el-button type="primary" @click="handleAddSku(row)">添加SKU</el-button>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="id" label="商品ID" width="80" />
        <el-table-column prop="name" label="商品名称" min-width="180" show-overflow-tooltip />
        <el-table-column prop="categoryName" label="分类" width="120" />
        <el-table-column label="主图" width="100">
          <template #default="{ row }">
            <el-image
              v-if="row.mainImage"
              :src="row.mainImage"
              :preview-src-list="[row.mainImage]"
              fit="cover"
              class="product-image"
            />
            <span v-else>暂无图片</span>
          </template>
        </el-table-column>
        <el-table-column label="价格" width="120">
          <template #default="{ row }">
            <span class="price">¥{{ formatPrice(row.price) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'info'">
              {{ row.status === 1 ? '上架' : '下架' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="是否新品" width="100">
          <template #default="{ row }">
            <el-tag :type="row.isNew === 1 ? 'warning' : 'info'">
              {{ row.isNew === 1 ? '新品' : '普通' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleEdit(row)">编辑</el-button>
            <el-button type="success" link @click="handleComments(row)">评论管理</el-button>
            <el-button
              :type="row.status === 1 ? 'warning' : 'success'"
              link
              @click="handleToggleStatus(row)"
            >
              {{ row.status === 1 ? '下架' : '上架' }}
            </el-button>
            <el-button type="danger" link @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          background
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- SKU编辑对话框 -->
    <el-dialog
      v-model="skuDialogVisible"
      :title="skuDialogType === 'add' ? '添加SKU' : '编辑SKU'"
      width="600px"
      destroy-on-close
    >
      <el-form
        ref="skuFormRef"
        :model="skuForm"
        :rules="skuRules"
        label-width="100px"
        :validate-on-rule-change="false"
      >
        <el-form-item label="规格" prop="specValues">
          <div class="spec-selector">
            <div v-if="Object.keys(skuForm.specValues || {}).length > 0" class="selected-specs">
              <el-tag
                v-for="(value, name) in skuForm.specValues || {}"
                :key="name"
                class="spec-tag"
                closable
                @close="removeSpec(name)"
              >
                {{ name }}: {{ value }}
              </el-tag>
            </div>
            <div class="spec-list">
              <div v-for="spec in selectedSpecs" :key="spec.id" class="spec-item">
                <div class="spec-name">{{ spec.name }}</div>
                <div class="spec-values">
                  <el-tag
                    v-for="value in spec.values"
                    :key="value"
                    :class="{ 'is-selected': isValueSelected(spec.name, value) }"
                    class="spec-value-tag"
                    @click="selectSpecValue(spec, value)"
                  >
                    {{ value }}
                  </el-tag>
                </div>
              </div>
            </div>
          </div>
        </el-form-item>

        <el-form-item label="SKU名称" prop="skuName">
          <el-input v-model="skuForm.skuName" placeholder="请输入SKU名称" />
        </el-form-item>

        <el-form-item label="SKU图片">
          <el-upload
            class="sku-image-uploader"
            :show-file-list="false"
            :http-request="uploadSkuImage"
            :before-upload="beforeSkuImageUpload"
          >
            <img v-if="skuForm.image" :src="skuForm.image" fit="cover" class="sku-form-image" />
            <el-icon v-else class="upload-icon"><Plus /></el-icon>
          </el-upload>
          <div class="upload-tip">支持 JPG/PNG/GIF 格式，大小不超过 2MB</div>
        </el-form-item>

        <el-form-item label="价格" prop="price">
          <el-input-number
            v-model="skuForm.price"
            :min="0"
            :precision="2"
            :step="0.1"
            controls-position="right"
          />
        </el-form-item>

        <el-form-item label="库存" prop="stock">
          <el-input-number
            v-model="skuForm.stock"
            :min="0"
            :precision="0"
            :step="1"
            controls-position="right"
          />
        </el-form-item>

        <el-form-item label="状态">
          <el-switch
            v-model="skuForm.status"
            :active-value="1"
            :inactive-value="0"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="skuDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitSku">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { 
  getMerchantProducts, 
  deleteProduct, 
  updateProductStatus,
  getMerchantSkus,
  createSku,
  updateSku,
  uploadProductImage,
  getMerchantSpecTemplates,
  getGlobalSpecTemplates
} from '@/api/product'
import { getCategoryTree } from '@/api/category'
import { useUserStore } from '@/stores/user'

const router = useRouter()
const userStore = useUserStore()

// 状态定义
const loading = ref(false)
const productList = ref([])
const categories = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 搜索表单
const searchForm = ref({
  name: '',
  categoryId: '',
  status: ''
})

// SKU对话框相关
const skuDialogVisible = ref(false)
const skuDialogType = ref('add')
const skuFormRef = ref(null)
const currentProduct = ref(null)
const currentSku = ref(null)
const selectedSpecs = ref([])

const skuForm = ref({
  id: null,
  productId: null,
  skuName: '',
  specValues: {},
  specs: {},
  image: '',
  price: 0,
  stock: 0,
  status: 1
})

const skuRules = {
  skuName: [
    { required: true, message: '请输入SKU名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  specValues: [
    { required: true, message: '请选择规格值', trigger: 'change', type: 'object' }
  ],
  price: [
    { required: true, message: '请输入价格', trigger: 'blur', type: 'number' },
    { type: 'number', min: 0, message: '价格必须大于等于0', trigger: 'blur' }
  ],
  stock: [
    { required: true, message: '请输入库存', trigger: 'blur', type: 'number' },
    { type: 'number', min: 0, message: '库存必须大于等于0', trigger: 'blur' }
  ]
}

// 获取商品列表
const fetchProducts = async () => {
  try {
    loading.value = true
    const params = {
      pageNum: currentPage.value,
      pageSize: pageSize.value,
      name: searchForm.value.name || undefined,
      categoryId: searchForm.value.categoryId || undefined,
      status: searchForm.value.status
    }
    
    // 移除值为undefined的参数
    Object.keys(params).forEach(key => {
      if (params[key] === undefined) {
        delete params[key]
      }
    })

    const res = await getMerchantProducts(params)
    
    if (res?.code === 200 && res.data) {
      productList.value = res.data.records || []
      total.value = res.data.total || 0
    } else {
      productList.value = []
      total.value = 0
      ElMessage.warning(res?.message || '暂无商品数据')
    }
  } catch (error) {
    console.error('获取商品列表失败:', error)
    ElMessage.error('获取商品列表失败')
    productList.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

// 获取分类列表
const fetchCategories = async () => {
  try {
    const res = await getCategoryTree()
    if (res?.code === 200 && res.data) {
      categories.value = flattenCategoryTree(res.data)
    }
  } catch (error) {
    console.error('获取分类列表失败:', error)
    ElMessage.error('获取分类列表失败')
    categories.value = []
  }
}

// 将分类树扁平化为列表
const flattenCategoryTree = (tree) => {
  const result = []
  const flatten = (items, parentName = '') => {
    items.forEach(item => {
      const fullName = parentName ? `${parentName} / ${item.name}` : item.name
      result.push({
        id: item.id,
        name: fullName
      })
      if (item.children && item.children.length > 0) {
        flatten(item.children, fullName)
      }
    })
  }
  flatten(tree)
  return result
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  fetchProducts()
}

// 重置搜索
const resetSearch = () => {
  searchForm.value = {
    name: '',
    categoryId: '',
    status: ''
  }
  currentPage.value = 1
  fetchProducts()
}

// 添加商品
const handleAdd = () => {
  router.push('/merchant/product/add')
}

// 编辑商品
const handleEdit = (row) => {
  router.push(`/merchant/product/edit/${row.id}`)
}

// 切换商品状态
const handleToggleStatus = async (row) => {
  try {
    const newStatus = row.status === 1 ? 0 : 1
    const actionText = newStatus === 1 ? '上架' : '下架'
    
    await ElMessageBox.confirm(`确定要${actionText}该商品吗？`, '提示', {
      type: 'warning'
    })
    
    await updateProductStatus(row.id, { enabled: newStatus === 1 })
    ElMessage.success(`${actionText}成功`)
    fetchProducts()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('操作失败:', error)
      ElMessage.error('操作失败')
    }
  }
}

// 删除商品
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除该商品吗？删除后不可恢复！', '警告', {
      type: 'warning'
    })
    
    await deleteProduct(row.id)
    ElMessage.success('删除成功')
    fetchProducts()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 分页相关
const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
  fetchProducts()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchProducts()
}

// 格式化日期
const formatDate = (dateArray) => {
  if (!dateArray || !Array.isArray(dateArray)) return '暂无'
  const [year, month, day, hour, minute, second] = dateArray
  return `${year}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')} ${String(hour).padStart(2, '0')}:${String(minute).padStart(2, '0')}:${String(second).padStart(2, '0')}`
}

// 格式化价格
const formatPrice = (price) => {
  return Number(price).toFixed(2)
}

// 处理展开行变化
const handleExpandChange = async (row, expandedRows) => {
  // 保存展开状态
  row.isExpanded = expandedRows.includes(row)
  
  if (row.isExpanded && !row.skuList) {
    try {
      row.skuLoading = true
      const res = await getMerchantSkus({ 
        productId: row.id,
        pageNum: 1,
        pageSize: 100 // 获取较多SKU以显示完整列表
      })
      if (res?.code === 200 && res.data) {
        row.skuList = res.data.records || []
      } else {
        row.skuList = []
      }
    } catch (error) {
      console.error('获取SKU列表失败:', error)
      ElMessage.error('获取SKU列表失败')
      row.skuList = []
    } finally {
      row.skuLoading = false
    }
  }
}

// 获取规格列表
const fetchSpecTemplates = async (product) => {
  try {
    if (!product.specs) {
      selectedSpecs.value = []
      return
    }

    try {
      const productSpecs = JSON.parse(product.specs)
      selectedSpecs.value = productSpecs.map(spec => ({
        name: spec.name,
        values: spec.values
      }))
    } catch (e) {
      console.error('解析商品规格数据失败:', e)
      selectedSpecs.value = []
    }
  } catch (error) {
    console.error('获取规格列表失败:', error)
    ElMessage.error('获取规格列表失败')
    selectedSpecs.value = []
  }
}

// 添加SKU
const handleAddSku = async (product) => {
  currentProduct.value = product
  currentSku.value = null
  skuDialogType.value = 'add'
  skuForm.value = {
    id: null,
    productId: product.id,
    skuName: '',
    specValues: {},
    image: '',
    price: 0,
    stock: 0,
    status: 1
  }
  await fetchSpecTemplates(product)
  skuDialogVisible.value = true
}

// 编辑SKU
const handleEditSku = async (product, sku) => {
  currentProduct.value = product
  currentSku.value = sku
  skuDialogType.value = 'edit'
  skuForm.value = {
    id: sku.id,
    productId: product.id,
    skuName: sku.skuName,
    specValues: parseSpecValues(sku.specValues),
    image: sku.image,
    price: sku.price,
    stock: sku.stock,
    status: sku.status
  }
  await fetchSpecTemplates(product)
  skuDialogVisible.value = true
}

// 切换SKU状态
const handleToggleSkuStatus = async (product, sku) => {
  try {
    const newStatus = sku.status === 1 ? 0 : 1
    const actionText = newStatus === 1 ? '启用' : '禁用'
    
    await ElMessageBox.confirm(`确定要${actionText}该SKU吗？`, '提示', {
      type: 'warning'
    })
    
    await updateSku({
      id: sku.id,
      productId: product.id,
      status: newStatus,
      skuName: sku.skuName,
      specValues: typeof sku.specValues === 'string' ? sku.specValues : JSON.stringify(sku.specValues),
      price: sku.price,
      stock: sku.stock,
      image: sku.image
    })
    
    ElMessage.success(`${actionText}成功`)
    await refreshSkuList(product)
  } catch (error) {
    if (error !== 'cancel') {
      console.error('操作失败:', error)
      ElMessage.error('操作失败')
    }
  }
}

// 删除SKU
const handleDeleteSku = async (product, sku) => {
  try {
    await ElMessageBox.confirm('确定要删除该SKU吗？删除后不可恢复！', '警告', {
      type: 'warning'
    })
    
    await updateSku({
      id: sku.id,
      productId: product.id,
      deleted: true,
      skuName: sku.skuName,
      specValues: typeof sku.specValues === 'string' ? sku.specValues : JSON.stringify(sku.specValues),
      price: sku.price,
      stock: sku.stock,
      image: sku.image,
      status: sku.status
    })
    
    ElMessage.success('删除成功')
    await refreshSkuList(product)
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 修改上传处理函数
const uploadSkuImage = async (params) => {
  try {
    const res = await uploadProductImage(params.file)
    if (res.code === 200 && res.data) {
      skuForm.value.image = res.data
      ElMessage.success('图片上传成功')
    } else {
      ElMessage.error(res?.message || '上传失败')
    }
  } catch (error) {
    console.error('上传失败:', error)
    ElMessage.error('上传失败')
  }
}

// 提交SKU表单
const submitSku = async () => {
  if (!skuFormRef.value) return
  
  try {
    await skuFormRef.value.validate()
    
    // 检查是否有选择规格值
    if (Object.keys(skuForm.value.specValues || {}).length === 0) {
      ElMessage.warning('请至少选择一个规格值')
      return
    }

    // 构造提交数据
    const submitData = {
      productId: currentProduct.value.id,
      skuName: skuForm.value.skuName,
      specValues: JSON.stringify(skuForm.value.specValues),
      price: skuForm.value.price,
      stock: skuForm.value.stock,
      status: skuForm.value.status,
      image: skuForm.value.image
    }
    
    if (skuDialogType.value === 'add') {
      const res = await createSku(submitData)
      if (res.code === 200 && res.data) {
        ElMessage.success('添加成功')
        await refreshSkuList(currentProduct.value)
      }
    } else {
      submitData.id = skuForm.value.id
      const res = await updateSku(submitData)
      if (res.code === 200 && res.data) {
        ElMessage.success('更新成功')
        await refreshSkuList(currentProduct.value)
      }
    }
    
    // 关闭编辑对话框
    skuDialogVisible.value = false
  } catch (error) {
    console.error('提交失败:', error)
    ElMessage.error(error.message || '提交失败，请检查表单')
  }
}

// 刷新SKU列表
const refreshSkuList = async (product) => {
  try {
    const res = await getMerchantSkus({ 
      productId: product.id,
      pageNum: 1,
      pageSize: 100 // 获取较多SKU以显示完整列表
    })
    if (res?.code === 200 && res.data) {
      product.skuList = res.data.records || []
    } else {
      product.skuList = []
    }
  } catch (error) {
    console.error('刷新SKU列表失败:', error)
    ElMessage.error('刷新SKU列表失败')
  }
}

// 检查规格值是否已选中
const isValueSelected = (specName, value) => {
  return skuForm.value.specValues[specName] === value
}

// 选择规格值
const selectSpecValue = (spec, value) => {
  if (skuForm.value.specValues[spec.name] === value) {
    // 如果已经选中了这个值，则取消选择
    delete skuForm.value.specValues[spec.name]
  } else {
    // 否则选中这个值
    skuForm.value.specValues[spec.name] = value
  }
}

// 移除规格
const removeSpec = (name) => {
  delete skuForm.value.specValues[name]
}

// 解析规格值
const parseSpecValues = (specValuesStr) => {
  try {
    return specValuesStr ? JSON.parse(specValuesStr) : {}
  } catch (e) {
    console.error('解析规格值失败:', e)
    return {}
  }
}

// 管理评论
const handleComments = (row) => {
  router.push(`/merchant/product/comment/${row.id}`)
}

onMounted(() => {
  fetchCategories()
  fetchProducts()
})
</script>

<style scoped>
.product-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-form {
  margin-bottom: 20px;
  padding: 20px;
  background-color: var(--el-fill-color-light);
  border-radius: 4px;
}

.pagination-container {
  margin-top: 20px;
  padding: 10px 20px;
  display: flex;
  justify-content: flex-end;
}

.price {
  color: var(--el-color-danger);
  font-weight: bold;
}

.product-image {
  width: 60px;
  height: 60px;
  border-radius: 4px;
}

.sku-expand {
  padding: 20px;
}

.sku-specs {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.sku-spec-tag {
  margin-right: 4px;
}

.sku-image {
  width: 50px;
  height: 50px;
  object-fit: cover;
}

.no-sku {
  text-align: center;
  color: #909399;
  padding: 20px;
}

.sku-actions {
  margin-top: 16px;
  display: flex;
  justify-content: flex-end;
}

.spec-selector {
  border: 1px solid var(--el-border-color-light);
  border-radius: 4px;
  padding: 16px;
}

.selected-specs {
  margin-bottom: 16px;
  padding-bottom: 16px;
  border-bottom: 1px solid var(--el-border-color-lighter);
}

.spec-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.spec-item {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.spec-name {
  font-weight: bold;
  color: var(--el-text-color-primary);
}

.spec-values {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.spec-value-tag {
  cursor: pointer;
  transition: all 0.3s;
}

.spec-value-tag:hover {
  background-color: var(--el-color-primary-light-8);
}

.spec-value-tag.is-selected {
  background-color: var(--el-color-primary);
  color: white;
}

.sku-image-uploader {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 100px;
  height: 100px;
}

.sku-image-uploader:hover {
  border-color: var(--el-color-primary);
}

.upload-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  text-align: center;
  line-height: 100px;
}

.sku-form-image {
  width: 100px;
  height: 100px;
  object-fit: cover;
}

.upload-tip {
  margin-top: 8px;
  font-size: 0.8em;
  color: #909399;
}
</style> 